<template>
  <div class="config-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>配置管理</h3>
          <el-button type="primary" @click="handleAdd">+ 添加配置项</el-button>
        </div>
      </template>

      <el-table :data="configList" border v-loading="loading">
        <el-table-column prop="id" label="ID编号" width="80" align="center" />
        <el-table-column prop="title" label="配置名称" width="200" />
        <el-table-column prop="name" label="配置标识">
          <template #default="scope">
            {{ scope.row.name }}
            <span class="red">（新增的模板文件名称需与标识名称一致）</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleView(scope.row)">查看</el-button>
            <el-dropdown>
              <el-button size="small">
                更多
                <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="edit" @click="() => handleEdit(scope.row)">
                    修改
                  </el-dropdown-item>
                  <el-dropdown-item command="editConfig" @click="() => handleEditConfig(scope.row)">
                    编辑配置
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="delete"
                    @click="() => handleDelete(scope.row)"
                    :disabled="scope.row.id === 1"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑配置项对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="100px">
        <el-form-item label="配置名称" prop="title">
          <el-input v-model="configForm.title" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置标识" prop="name">
          <el-input v-model="configForm.name" placeholder="请输入配置标识" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="configForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitConfig">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { homeApi } from '@/api/home'

  // 数据相关
  const configList = ref([])
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const dialogTitle = ref('')
  const isEdit = ref(false)

  // 表单数据
  const configForm = reactive({
    id: 0,
    title: '',
    name: '',
    status: 1,
  })

  // 表单验证规则
  const configRules = {
    title: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
  }

  // 表单引用
  const configFormRef = ref()

  // 获取配置列表
  const getConfigListData = async () => {
    try {
      loading.value = true
      const response: any = await homeApi.getConfigList()
      if (response.code === 0) {
        configList.value = response.data
      } else {
        ElMessage.error(response.msg || '获取配置列表失败')
      }
    } catch (error) {
      ElMessage.error('获取配置列表失败')
    } finally {
      loading.value = false
    }
  }

  // 处理添加配置
  const handleAdd = () => {
    dialogTitle.value = '添加配置项'
    isEdit.value = false
    // 重置表单
    Object.assign(configForm, {
      id: 0,
      title: '',
      name: '',
      status: 1,
    })
    dialogVisible.value = true
  }

  // 处理编辑配置
  const handleEdit = (row: any) => {
    dialogTitle.value = '编辑配置项'
    isEdit.value = true
    // 填充表单数据
    Object.assign(configForm, row)
    dialogVisible.value = true
  }

  // 编辑配置内容
  const handleEditConfig = (row: any) => {
    ElMessageBox.prompt('请输入配置内容', '编辑配置', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S/,
      inputErrorMessage: '配置内容不能为空',
    })
      .then(async () => {
        // 这里应该调用更新配置内容的API
        ElMessage.info(`编辑配置 ${row.title} 功能待实现`)
      })
      .catch(() => {
        // 用户取消操作
      })
  }

  // 查看配置详情
  const handleView = (row: any) => {
    // 显示配置详情，这里使用与编辑相同的对话框，但设置为只读模式
    dialogTitle.value = '查看配置项'
    isEdit.value = false
    // 填充表单数据
    Object.assign(configForm, row)
    // 设置对话框为只读模式
    configFormRef.value?.setReadOnly?.(true)
    dialogVisible.value = true
  }

  // 处理删除配置
  const handleDelete = (row: any) => {
    ElMessageBox.confirm('确认删除该配置项吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          const response: any = await homeApi.deleteConfig({ id: row.id })
          if (response.code === 0) {
            ElMessage.success('删除成功')
            await getConfigListData()
          } else {
            ElMessage.error(response.msg || '删除失败')
          }
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 提交配置
  const submitConfig = async () => {
    if (!configFormRef.value) return

    try {
      await configFormRef.value.validate()

      let response: any

      if (isEdit.value) {
        response = await homeApi.editConfig({
          id: configForm.id,
          title: configForm.title,
          name: configForm.name,
          status: configForm.status,
        })
      } else {
        response = await homeApi.saveConfig({
          title: configForm.title,
          name: configForm.name,
          status: configForm.status,
        })
      }
      if (response.code === 0) {
        ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
        dialogVisible.value = false
        await getConfigListData()
      } else {
        ElMessage.error(response.msg || (isEdit.value ? '编辑失败' : '添加失败'))
      }
    } catch (error) {
      ElMessage.error(isEdit.value ? '编辑失败' : '添加失败')
    }
  }

  // 对话框关闭时重置表单
  const handleDialogClose = () => {
    configFormRef.value?.resetFields()
  }

  // 组件挂载时获取数据
  onMounted(() => {
    getConfigListData()
  })
</script>

<style scoped>
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .red {
    color: #f56c6c;
  }
</style>
